package com.tanhua.server.controller;

import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.domain.vo.UserInfoVo;
import com.tanhua.server.service.UserInfoService;
import io.jsonwebtoken.Claims;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * @author 妙妙
 * @title UsersControler
 * @date 2025/7/13 19:30
 * @description TODO
 */
@RestController
@RequestMapping("/users")
public class UsersControler {

    private final UserInfoService userInfoService;

    public UsersControler(UserInfoService userInfoService) {
        this.userInfoService = userInfoService;
    }

    /**
     * 获取用户信息
     * @return
     */
    @GetMapping()
    public ResponseEntity getUserInfo(
            @RequestHeader("Authorization") String token,
            Long userId
    ){
        //1、判断 token是否合法
        if (!JwtUtils.verifyToken(token)) {
            return ResponseEntity.status(401).body(null);
        }

        //1、解析token
        Claims claims = JwtUtils.getClaims(token);
        Integer id = (Integer) claims.get("id");

        if (userId == null){
            userId = Long.valueOf(id);
        }
        UserInfoVo vo = userInfoService.findById(userId);

        return ResponseEntity.ok(vo);
    }

    /**
     * 更新个人资料
     */
    @PutMapping ()
    public ResponseEntity updateUserInfo(
            @RequestBody UserInfo userInfo,
            @RequestHeader("Authorization") String token
    ){
        //1、判断 token是否合法
        if (!JwtUtils.verifyToken(token)) {
            return ResponseEntity.status(401).body(null);
        }

        //1、解析token 获取id
        Claims claims = JwtUtils.getClaims(token);
        Integer id = (Integer) claims.get("id");

        userInfo.setId(Long.valueOf(id));
        userInfoService.updateLL(userInfo);
        return ResponseEntity.ok(null);

    }


}
